<template>
  <ElInput :value="label" :placeholder="`请选择${column.label}`" readonly @click="onClick">
    <template #append>
      <ElButton @click="onClick">选择</ElButton>
    </template>
  </ElInput>
</template>
<script setup lang="ts">
  import { h, ref } from 'vue'
  import { ElInput, ElButton } from 'element-plus'
  import { footer, popup } from "@/components/Popup"
  import { Column, ShowPosition } from '@/seed-application/types'
  import { watch } from 'vue';
  import { TreePanel } from '@/components/Panel';

  const props = defineProps<{
    column: Column,
    modelValue?: any,
    label?: string,
    position?: ShowPosition
    popupProps?: Record<string, any>
  }>()
  const emits = defineEmits(['update:modelValue'])
  const column = props.column

  const value = ref()
  const label = ref()
  let chooseLabel
  watch(() => props.modelValue, (val) =>  value.value = val, { immediate: true })
  watch(() => props.label, (val) => {
    label.value = val
    chooseLabel = val
  }, { immediate: true })

  const onClick = () => {
    const popupProps = {
      title: props.popupProps?.title || `请选择${column.label}`,
      position: props.position,
      maxHeight: props.popupProps?.maxHeight,
      width: props.popupProps?.width
    }
    popup(popupProps, {
      default: () => h(TreePanel, {column, value: value.value, onChoose}),
      footer: footer(ok)
    })
  }

  const onChoose = (val, lbl) => {
    console.log('lookup tree onChoose', val, lbl)
    value.value = val
    chooseLabel = lbl
  }

  function ok() {console.log('lookup tree ok', chooseLabel)
    label.value = chooseLabel
    emits('update:modelValue', value.value)
  }
</script>
